package com.ljh.protocol;

import com.ljh.message.LoginRequestMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author: Themberfue
 * @date: 2025/5/28 21:41
 * @description:
 */
public class TestMessageCodec {
    public static void main(String[] args) throws Exception {
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(
                // ! 解决半包粘包问题
                // ! 尽管是自定义协议，也还是会出现，由于 TCP 协议和 MTU 限制
                // ! 使用 LTC 编解码器，根据解码器的规则读到了完整一条数据才真正从缓冲区读出
                new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0),
                new LoggingHandler(),
                new MessageCodec()
        );

        // TODO 1. encode
        LoginRequestMessage message = new LoginRequestMessage("张三", "123");
        embeddedChannel.writeOutbound(message);

        // TODO 2. decode
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        new MessageCodec().encode(null, message, buf);
        embeddedChannel.writeInbound(buf);
    }
}
